package main

import (
	"fmt"
	"sync"
	"time"
)

var myMap = make(map[int]int, 10)

//声明全局互斥锁
var lock sync.Mutex

//阶乘
func test(n int) {
	res := 1
	for i := 1; i <= n; i++ {
		res *= i
	}
	//枷锁
	lock.Lock()
	myMap[n] = res //concurrent map writes
	lock.Unlock()
}

/*func factorial(num int) {
	sum := 1
	numMap := make(map[int]int, 10)
	for i := 1; i <= num; i++ {
		for j := 1; j <= i; j++ {
			sum = sum * j
		}
		numMap[i] = sum
	}
	fmt.Println(numMap)
}*/
func main() {
	for i := 0; i < 20; i++ {
		go test(i)
	}
	time.Sleep(time.Second * 10)
	lock.Lock()
	for i, i2 := range myMap {
		fmt.Printf("key：%v value:%v\n", i, i2)
	}
	lock.Unlock()
}
